package com.freework.util.listUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.freework.util.FileUtil;
import com.freework.util.MapUtil;
import com.freework.util.listUtil.SortList.ItemType;
import com.freework.util.listUtil.group.AggregateCol;
import com.freework.util.listUtil.group.GroupCol;
import com.freework.util.listUtil.group.GroupKey;

public class ListUtil {
	public static void main(String args[]){

		
		//List<Map> list=new ArrayList<Map>();
		//for (int i = 0; i < 5; i++) {
			List<Map> list=Arrays.asList(
					MapUtil.asMap2("aa","001001","b","01","sum",1,"a",1),
					MapUtil.asMap2("aa","001002","b","02","sum",1,"a",1),
					MapUtil.asMap2("aa","032001","b","01","sum",1,"a",1),
					MapUtil.asMap2("aa","020101","b","5","sum",1,"a",1));
		//	list.addAll(list1);
		//}
			GroupCol[] cols={GroupCol.col("aa",3,3)};
			AggregateCol AggregateCols[]={
			 new AggregateCol("sum,a","sum{b}")
		//	,new AggregateCol("convention,aaa","ee")
		//	,new AggregateCol("append,b","appende")
		//	,new AggregateCol("mathe,a,+,b,*,a","max_sum")
			 };
			Collection list2= group(list,cols,AggregateCols);
System.out.println( JSON.toJSONString(list2));
		
	}
	
	
	
	
	public static Map mergerMap(int size, List<GroupKey> keys){
		Map mergerMap=new HashMap();
		for (int j = 0; j <=size; j++) {
			mergerMap.put(keys.get(j).name,keys.get(j).value);
		}
		return mergerMap;
	}
	
	
	
	public static  void sort(List list,ItemType itemtype, String... sortFieldName){
		SortList.sort(list, itemtype, sortFieldName);
	}
	
	
	
	
	
	public static Collection group(List<Map> list,GroupCol[] groupCols,AggregateCol[] aggregateCol){
		SortedMap<String, Map> groupMap = new TreeMap<String, Map>();
		for (Map map : list) {
			
				 List<GroupKey> keyList=GroupKey.getGroupKey(groupCols, map);
		int i=0;
			for (GroupKey groupKey2 : keyList) {
					//String key=keystr.toString();
					if(groupKey2.isData){
						String keystr=groupKey2.toString();
						Map mergerMap=groupMap.get(keystr);
						if(mergerMap==null){
							mergerMap=mergerMap(i,keyList);
							mergerMap.put("gourp_sys_level", i);
							groupMap.put(keystr, mergerMap);
						}
						for (int j = 0; j < aggregateCol.length; j++) {
							aggregateCol[j].setValue(map, mergerMap);
						}
					}
					i++;
			}
			
		}
		return groupMap.values();
		
	}
}
